import functools
from app.models import *
from app import app
import time
from flask import make_response,request,jsonify,redirect,url_for

def user_require(func):
    @functools.wraps(func)
    def decorator(*args,**kwargs):
        uid = request.cookies.get("uid")
        if not uid:
            resp = make_response(jsonify({
                'code': -101,
                'msg': '请登录！'
            }))

            resp.delete_cookie("uid")
            return resp

        cookie = User_Cookies.query.filter_by(cookies=uid).first()
        if not cookie:
            resp = make_response(jsonify({
                'code': -101,
                'msg': '请登录！'
            }))
            resp.delete_cookie("uid")
            return resp
        if datetime.datetime.now() < cookie.endTime:
            user = cookie.user
            cookie.endTime = (datetime.datetime.now()+app.config['PEMEMBER_COOKIE_DURATION']).timetuple()
            db.session.commit()
            return func(*args, **kwargs,uid = user)

        else:
            resp = make_response(jsonify({
                'code': -101,
                'msg': '请登录！'
            }))

            resp.delete_cookie("uid")

            return resp

    return decorator

